use aes::Aes128;
use block_modes::{BlockMode, Cbc};
use block_modes::block_padding;
/// 
/// 
/// 
/// 
type Aes128Cbc = Cbc<Aes128, block_padding::Pkcs7>;

pub fn encrypt(plaindata: &Vec<u8>, key: &[u8], iv: &[u8]) -> Vec<u8> {
    // create an alias for convenience
    let cipher = Aes128Cbc::new_var(&key, &iv).unwrap();

    let ciphertext = cipher.encrypt_vec(&plaindata);
    ciphertext
}

pub fn decrypt(cipherdata: &Vec<u8>, key: &[u8], iv: &[u8]) -> Vec<u8> {
    let cipher = Aes128Cbc::new_var(key, iv).unwrap();
    let plaindata = cipher.decrypt_vec(cipherdata).unwrap();
    plaindata
}

#[cfg(test)]
mod tests {
    use hex_literal::hex;
    #[test]
    fn it_works() {
        let key = hex!("013F65A3AE564CA02D5215C36D71DBB3");
        let iv = hex!("013F6543AE564CA01D5215C36D71DBB3");

        let plaindata = b"test aes cfbabcf";

        let cipherdata = [
            199, 153, 183, 166, 172, 166, 125, 3, 143, 129, 52, 111, 117, 195, 134, 19,
            47, 138, 246, 13, 50, 48, 20, 235, 157, 87, 3, 235, 18, 206, 55, 248
        ];
        let cipherdata2 = super::encrypt(&plaindata.to_vec(), &key, &iv);
        let plaindata2 = super::decrypt(&cipherdata.to_vec(), &key, &iv);
        println!("cipherdata2: {:?}", cipherdata2);
        assert_eq!(cipherdata.to_vec() , cipherdata2);
        assert_ne!(cipherdata.len(), plaindata.len());
        assert_eq!(plaindata.to_vec() , plaindata2);
    }
}